package com.test.mchelepesa.activity_fragment_rice.base_rice;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.test.mchelepesa.R;
import com.test.mchelepesa.activity_fragment_rice.info_rice.BindAccountActivity_rice;
import com.test.mchelepesa.activity_fragment_rice.info_rice.FaceInfoActivity_rice;
import com.test.mchelepesa.activity_fragment_rice.info_rice.InfoUploadActivity_rice;
import com.test.mchelepesa.activity_fragment_rice.info_rice.OcrInfoActivity_rice;
import com.test.mchelepesa.activity_fragment_rice.loan_rice.LoanApplyActivity_rice;
import com.test.mchelepesa.activity_fragment_rice.loan_rice.LoanMainActivity_rice;
import com.test.mchelepesa.activity_fragment_rice.login_rice.LoginPhoneNumActivity_rice;
import com.test.mchelepesa.activity_fragment_rice.login_rice.VerificationActivity;
import com.test.mchelepesa.bean_rice.StaticConfig_rice;
import com.test.mchelepesa.bean_rice.config_info_rice.GlobalConfig_rice;
import com.test.mchelepesa.bean_rice.process_rice.ProcessInfo_rice;
import com.test.mchelepesa.constant_rice.Constant_rice;
import com.test.mchelepesa.util_rice.PermissionUtil_rice;
import com.test.mchelepesa.util_rice.StringUtil_rice;
import com.test.mchelepesa.util_rice.ThreadUtil_rice;
import com.test.mchelepesa.util_rice.helper_rice.ActivityHelper_rice;
import com.test.mchelepesa.util_rice.helper_rice.UserInfoHelper_rice;
import com.test.mchelepesa.util_rice.http_rice.HttpManager_rice;
import com.test.mchelepesa.util_rice.http_rice.HttpPresenter_rice;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;

import pub.devrel.easypermissions.EasyPermissions;


public abstract class BaseActivity_rice extends AppCompatActivity implements EasyPermissions.PermissionCallbacks, EasyPermissions.RationaleCallbacks {

    private Toast toast_rice;

    public static Bitmap companyLogo;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (!Constant_rice.Debug) getWindow().addFlags(WindowManager.LayoutParams.FLAG_SECURE);
    }

    //页面埋点
    public void recordPagePauseEvent_rice() {
        //保存埋点
        String activityName = getClass().getSimpleName();
        if (!TextUtils.isEmpty(activityName)) {
            if (this instanceof LoanMainActivity_rice loanMainActivity && loanMainActivity.isRepayOverdue())
                HttpManager_rice.getInstance().saveUserBuriedPointAndUpload((activityName + "_END").toUpperCase());
            else HttpManager_rice.getInstance().saveUserBuriedPoint((activityName + "_END").toUpperCase());
        }
    }

    //借款流程
    public void startLoanProcess() {

        String currentStepName = ProcessInfo_rice.getInstance().getCurrentStepName();

        if (TextUtils.isEmpty(currentStepName))//流程上报完毕
            startActivity_rice(LoanApplyActivity_rice.class);
        else {

            switch (currentStepName){
                case "ocr_info":
                    startActivity_rice(OcrInfoActivity_rice.class);
                    break;
                case "sefie_info":
                    startActivity_rice(FaceInfoActivity_rice.class);
                    break;
                case "account_info":
                    if (StaticConfig_rice.isSpecialBindAccount()){
                        startActivity_rice(BindAccountActivity_rice.class);
                        break;
                    }
                default:
                    startActivity_rice(InfoUploadActivity_rice.class);
            }

        }

        if (this instanceof BaseInfoActivity_rice) finish();

    }

    //处理用户流程状态
    public void onUserProcessResponse_rice() {

        if (ProcessInfo_rice.getInstance().isNeedVerification()){
            UserInfoHelper_rice.getInstance().setVerificationFlag(Constant_rice.VerificationFlag_HOME);
            startActivityForSingleTop_rice(VerificationActivity.class);
            return;
        }

        startActivityForSingleTop_rice(LoanMainActivity_rice.class);
    }

    public void showToastOnUiThread_rice(String text) {
        runOnUiThread(() -> showToast_rice(text));
    }

    @Override
    protected void onResume() {
        super.onResume();
        HttpPresenter_rice.getInstance().setActivity(this);
        recordPageResumeEvent_rice();
    }

    public void showToast_rice(String text) {
        if (toast_rice == null) toast_rice = Toast.makeText(this, text, Toast.LENGTH_SHORT);
        else toast_rice.setText(text);
        toast_rice.show();
    }

    public <T extends BaseActivity_rice> void startActivityForSingleTop_rice(Class<T> activityClass) {
        Intent intent = new Intent(this, activityClass);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP);
        startActivity_rice(activityClass);
        finish();
    }

    public void setBackBtn_rice(View btnView) {
        btnView.setOnClickListener(view -> onBackPressed());
    }

    //页面埋点
    public void recordPageResumeEvent_rice() {
        //保存埋点
        String activityName = getClass().getSimpleName();
        if (!TextUtils.isEmpty(activityName)) {
            HttpManager_rice.getInstance().saveUserBuriedPoint((activityName + "_START").toUpperCase());
        }
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            View view = getCurrentFocus();
            if (view != null) {
                if (ActivityHelper_rice.canHideKeyboard(view, ev)) {
                    InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                    if (inputMethodManager != null) {
                        ActivityHelper_rice.hideKeyboard(this);
                        EditText editText = (EditText) view;
                        editText.clearFocus();
                    }
                }
            }
            return super.dispatchTouchEvent(ev);
        }
        return getWindow().superDispatchTouchEvent(ev) || onTouchEvent(ev);
    }


    public <T extends BaseActivity_rice> void startActivity_rice(Class<T> activityClass) {
        startActivity(new Intent(this, activityClass));
    }

    @Override
    protected void onPause() {
        super.onPause();
        HttpPresenter_rice.getInstance().setActivity(null);
        recordPagePauseEvent_rice();
    }

    //检测权限并申请未获取的权限
    public void requestLaunchPermissions_rice(String[] permissions) {
        EasyPermissions.requestPermissions(this, getString(R.string.launch_permissions_sms), PermissionUtil_rice.REQ_CODE_PERMISSIONS, permissions);
    }

//    //检测短信权限
    public void requestSMSPermissions_rice() {
        String[] permissions = new String[]{android.Manifest.permission.READ_SMS};
        EasyPermissions.requestPermissions(this, getString(R.string.launch_permissions_sms), PermissionUtil_rice.REQ_CODE_PERMISSIONS_SMS, permissions);
    }

    @Override
    public void onPermissionsGranted(int requestCode, @NonNull List<String> perms) {}

    @Override
    public void onPermissionsDenied(int requestCode, @NonNull List<String> perms) {}

    @Override
    public void onRationaleDenied(int requestCode) {}

    @Override
    public void onRationaleAccepted(int requestCode) {}

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

    public void initLicense(View licenseView,ImageView logoIv, TextView companyNameTv){

        String logoUrl = GlobalConfig_rice.getInstance().getCompanyLogo();
        String companyName = GlobalConfig_rice.getInstance().getCompanyName();

        if (TextUtils.isEmpty(logoUrl) || TextUtils.isEmpty(companyName)){
            licenseView.setVisibility(View.GONE);
            return;
        }

        licenseView.setVisibility(View.VISIBLE);

        if (companyLogo!=null) logoIv.setImageBitmap(companyLogo);
        else {
//            ThreadUtil_rice.getInstance().runOnChildThread(() -> {
//
//            });

            try {
                URL url = new URL(logoUrl);
                HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                connection.setConnectTimeout(5000);
                connection.setRequestMethod("GET");
                if (connection.getResponseCode()==200){
                    InputStream inputStream = connection.getInputStream();
                    companyLogo = BitmapFactory.decodeStream(inputStream);
                    ThreadUtil_rice.getInstance().runOnUiThread(() -> {
                        if (logoIv!=null) logoIv.setImageBitmap(companyLogo);
                    });
                }
            } catch (IOException e) {
                StringUtil_rice.printException(e);
            }
        }

        companyNameTv.setText(companyName);

    }

    public boolean isClose(){
        return isDestroyed() || isFinishing();
    }

    public void onUserCancel(){
        //删除本地登录信息
        UserInfoHelper_rice.getInstance().setMobile_rice("");
        UserInfoHelper_rice.getInstance().setToken_rice("");
        UserInfoHelper_rice.getInstance().setUserId_rice("");
        startActivityForSingleTop_rice(LoginPhoneNumActivity_rice.class);
    }

}